<template>
	<view class="confirm-page">
		<view class="address-card selectable" v-if="address" @click="chooseAddress">
			<view class="row">
				<text class="name">{{ address.receiver }}</text>
				<text class="phone">{{ address.phone }}</text>
			</view>
			<text class="detail">{{ formatAddress(address) }}</text>
		</view>
		<view class="address-card empty" v-else @click="chooseAddress">
			<text>暂无默认地址，请先添加收货地址</text>
		</view>

		<view class="item-card" v-for="item in items" :key="item.productId">
			<image class="pic" :src="getImageUrl(item.coverImage)" mode="aspectFill" />
			<view class="meta">
				<text class="title">{{ item.title }}</text>
				<text class="qty">数量：x{{ item.quantity }}</text>
			</view>
			<text class="price">¥{{ item.price }}</text>
		</view>

		<!-- 优惠券选择 -->
		<view v-if="type !== 'order'" class="coupon-card" @click="showCouponPicker">
			<view class="coupon-left">
				<text class="coupon-label">优惠券</text>
				<text v-if="selectedCoupon" class="coupon-name">{{ selectedCoupon.name }}</text>
				<text v-else class="coupon-placeholder">选择优惠券</text>
			</view>
			<text class="coupon-arrow">›</text>
		</view>

		<view class="summary">
			<view class="summary-row">
				<text>商品合计</text>
				<text class="amount">¥{{ originalAmount.toFixed(2) }}</text>
			</view>
			<view v-if="discountAmount > 0" class="summary-row discount-row">
				<text>优惠券减免</text>
				<text class="discount-amount">-¥{{ discountAmount.toFixed(2) }}</text>
			</view>
			<view class="summary-row total-row">
				<text>实付金额</text>
				<text class="total-amount">¥{{ finalAmount.toFixed(2) }}</text>
			</view>
		</view>

		<button class="submit" :disabled="submitting || !canSubmit" @click="submit">{{ submitText }}</button>
	</view>
</template>

<script>
import { api } from '../../utils/request.js'
import { BASE_URL } from '../../utils/server.js'

export default {
	data(){
		return {
			type: 'cart',
			items: [],
			selectedIds: [],
			address: null,
			orderId: null,
			submitting: false,
			orderCreated: false,
			availableCoupons: [],
			selectedCoupon: null,
			orderOriginalAmount: null,
			orderDiscountAmount: null
		}
	},
	computed:{
		originalAmount(){
			// 如果是支付页面，使用订单的原价
			if(this.type === 'order' && this.orderOriginalAmount !== null && this.orderOriginalAmount !== undefined){
				return Number(this.orderOriginalAmount);
			}
			return this.items.reduce((sum, item)=> sum + Number(item.price || 0) * Number(item.quantity || 1), 0);
		},
		discountAmount(){
			// 如果是支付页面，使用订单的优惠金额
			if(this.type === 'order' && this.orderDiscountAmount !== null && this.orderDiscountAmount !== undefined){
				return Number(this.orderDiscountAmount);
			}
			if (!this.selectedCoupon) return 0;
			return Number(this.selectedCoupon.discountAmount || 0);
		},
		finalAmount(){
			const amount = this.originalAmount - this.discountAmount;
			return amount > 0 ? amount : 0;
		},
		canSubmit(){
			if(this.type === 'order'){
				return !!this.orderId;
			}
			return this.items.length>0 && this.selectedIds.length>0 && !!this.address;
		},
		submitText(){
			if(this.type === 'order') return this.submitting ? '支付中...' : '立即支付';
			return this.submitting ? '提交中...' : '提交订单';
		}
	},
	onLoad(query){
		this.type = query?.type || 'cart';
		if(this.type === 'cart' && query?.selected){
			try{ const arr = JSON.parse(decodeURIComponent(query.selected)); this.selectedIds = (arr || []).map(v=>Number(v)); }catch{ this.selectedIds = []; }
		}
		if(this.type === 'single'){
			this.selectedIds = [];
			this.prepareSingle(query);
		}else if(this.type === 'order' && query?.order){
			try{
				const order = JSON.parse(decodeURIComponent(query.order));
				this.orderId = order.id;
				this.items = order.items || [];
				if(!this.items.length && order.product){
					this.items = [order.product];
				}
				// 保存订单的原价和优惠金额（用于显示）
				if(order.originalAmount){
					this.orderOriginalAmount = Number(order.originalAmount);
				}
				if(order.discountAmount){
					this.orderDiscountAmount = Number(order.discountAmount);
				}
			}catch{}
		}
		this.loadCartItemsIfNeeded();
		this.loadAddress();
	},
	onShow(){
		// 从优惠券选择页面返回时刷新可用优惠券
		if (this.items.length > 0) {
			this.loadAvailableCoupons();
		}
	},
	onUnload(){
		if(this.type === 'single' && !this.orderCreated){
			uni.showModal({ title:'提示', content:'商品已在购物车中，期待您的再次光临～', showCancel:false });
		}
	},
	methods:{
		formatAddress(addr){ return `${addr.province||''}${addr.city||''}${addr.district||''}${addr.detail||''}`; },
		async loadAddress(){
			try{
				const res = await api.getAddresses();
				if(res.code===0){
					const list = res.data || [];
					this.address = list.find(a=>a.isDefault===1) || list[0] || null;
				}
			}catch{}
		},
		chooseAddress(){
			uni.navigateTo({
				url: '/pages/address/choose',
				success: (res)=>{
					const ec = res.eventChannel;
					if(ec){ ec.on('chooseAddress', (addr)=>{ this.address = addr; }); }
				}
			});
		},
		async loadCartItemsIfNeeded(){
			if(this.type==='cart' && this.selectedIds.length){
				try{
					const cart = await api.cartList();
					if(cart.code===0){
						const list = cart.data.items || [];
						const result = [];
						for(const it of list){
							if(this.selectedIds.includes(it.productId)){
								const product = await this.ensureProduct(it.productId);
								result.push({ productId: it.productId, quantity: it.quantity, price: Number(product?.price||0), title: product?.title||`商品#${it.productId}`, coverImage: product?.coverImage||'' });
							}
						}
						this.items = result;
						// 加载可用优惠券
						this.loadAvailableCoupons();
					}
				}catch{}
			}
		},
		async prepareSingle(query){
			const productId = Number(query?.productId || 0);
			const quantity = Number(query?.quantity || 1);
			if(!productId) return;
			this.selectedIds = [productId];
			const product = await this.ensureProduct(productId);
			this.items = [{ productId, quantity, price: Number(product?.price||0), title: product?.title||`商品#${productId}`, coverImage: product?.coverImage||'' }];
			// 加载可用优惠券
			this.loadAvailableCoupons();
		},
		async ensureProduct(productId){
			try{
				const res = await api.getProduct(productId);
				if(res.code===0) return res.data;
			}catch{}
			return null;
		},
		async loadAvailableCoupons(){
			try{
				const res = await api.getAvailableCoupons(this.originalAmount.toFixed(2));
				if(res.code === 0){
					this.availableCoupons = res.data || [];
				}
			}catch(e){
				console.error('加载优惠券失败', e);
			}
		},
		showCouponPicker(){
			if(this.availableCoupons.length === 0){
				uni.showToast({ icon: 'none', title: '暂无可用优惠券' });
				return;
			}
			
			const couponList = this.availableCoupons.map(c => {
				const threshold = c.thresholdAmount > 0 ? `满${c.thresholdAmount}可用` : '无门槛';
				return `${c.name} - ${threshold} - 减¥${c.discountAmount}`;
			});
			
			uni.showActionSheet({
				itemList: ['不使用优惠券', ...couponList],
				success: (res) => {
					if(res.tapIndex === 0){
						this.selectedCoupon = null;
					} else {
						this.selectedCoupon = this.availableCoupons[res.tapIndex - 1];
					}
				}
			});
		},
		async submit(){
			if(!this.canSubmit || this.submitting) return;
			this.submitting = true;
			try{
				if(this.type==='order'){
					const res = await api.payOrder(this.orderId);
					if(res.code===0){
						uni.showToast({ title:'支付成功' });
						setTimeout(()=>{ uni.redirectTo({ url:'/pages/order/index?tab=pendingShip' }); }, 600);
					}else{
						uni.showToast({ icon:'none', title: res.message||'支付失败' });
					}
				}else{
					// 如果是立即购买（type=single），先确保购物车中有该商品且数量正确
					if(this.type === 'single' && this.items.length > 0){
						const item = this.items[0];
						try{
							// 先检查购物车中是否有该商品
							const cart = await api.cartList();
							if(cart.code === 0){
								const cartItems = cart.data.items || [];
								const existingItem = cartItems.find(ci => ci.productId === item.productId);
								if(existingItem){
									// 如果购物车中已有该商品，确保数量为1
									if(existingItem.quantity !== item.quantity){
										await api.cartUpdate({ productId: item.productId, quantity: item.quantity });
									}
								}else{
									// 如果购物车中没有该商品，添加它
									await api.cartAdd({ productId: item.productId, quantity: item.quantity });
								}
							}
						}catch(e){
							console.error('准备购物车失败', e);
						}
					}
					const payload = {
						productIds: this.selectedIds
					};
					if(this.selectedCoupon && this.selectedCoupon.userCouponId){
						payload.userCouponId = this.selectedCoupon.userCouponId;
					}
					const res = await api.checkoutSelected(payload);
					if(res.code===0){
						this.orderCreated = true;
						uni.showToast({ title:'下单成功' });
						setTimeout(()=>{ uni.redirectTo({ url:'/pages/order/index?tab=pendingPay' }); }, 600);
					}else{
						uni.showToast({ icon:'none', title: res.message||'下单失败' });
					}
				}
			}catch{
				uni.showToast({ icon:'none', title:this.type==='order' ? '支付失败' : '下单失败' });
			}
			finally{ this.submitting = false; }
		},
		getImageUrl(url) {
			if (!url) return '/static/logo.png';
			if (url.startsWith('http')) return url;
			return BASE_URL + url;
		}
	}
}
</script>

<style>
.confirm-page{ padding: 16rpx 16rpx 120rpx; display:flex; flex-direction: column; gap: 16rpx; }
.address-card{ background:#fff; border-radius: 18rpx; padding: 20rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.05); }
.address-card.empty{ color:#999; text-align:center; }
.row{ display:flex; justify-content: space-between; margin-bottom: 10rpx; color:#333; font-size: 28rpx; }
.detail{ color:#666; font-size: 26rpx; }
.item-card{ display:flex; align-items:center; gap: 16rpx; background:#fff; border-radius: 18rpx; padding: 20rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.05); }
.pic{ width: 140rpx; height: 140rpx; border-radius: 12rpx; background:#fafafa; }
.meta{ flex:1; }
.title{ font-size: 28rpx; color:#333; }
.qty{ font-size: 24rpx; color:#666; margin-top: 6rpx; }
.price{ font-size: 30rpx; color:#ff4d4f; font-weight: 600; }
.coupon-card{ display:flex; justify-content: space-between; align-items:center; background:#fff; border-radius: 18rpx; padding: 20rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.05); }
.coupon-left{ display:flex; flex-direction: column; gap: 8rpx; }
.coupon-label{ font-size: 28rpx; color:#333; }
.coupon-name{ font-size: 26rpx; color:#ff7a45; }
.coupon-placeholder{ font-size: 26rpx; color:#999; }
.coupon-arrow{ font-size: 32rpx; color:#999; }
.summary{ background:#fff; border-radius: 18rpx; padding: 20rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.05); display:flex; flex-direction: column; gap: 12rpx; }
.summary-row{ display:flex; justify-content: space-between; align-items:center; font-size: 28rpx; color:#333; }
.discount-row{ color:#ff7a45; }
.total-row{ padding-top: 12rpx; border-top: 1rpx solid #eee; font-size: 32rpx; font-weight: 600; }
.amount{ color:#333; }
.discount-amount{ color:#ff7a45; }
.total-amount{ color:#ff4d4f; font-weight: 700; }
.submit{ margin: 8rpx auto 0; background: linear-gradient(135deg,#ff7a45,#ff4d4f); color:#fff; border-radius: 20rpx; padding: 20rpx 0; font-size: 30rpx; width: 92%; }
.submit:disabled{ opacity:.5; }
</style>
